package com.yan.mvc.controller;

import com.yan.crowd.entity.Admin;
import com.yan.crowd.entity.Auth;
import com.yan.crowd.entity.Role;
import com.yan.crowd.util.ResultEntity;
import com.yan.service.AdminService;
import com.yan.service.AuthService;
import com.yan.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class AssignController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @ResponseBody
    @RequestMapping("assign/do/save/role/auth/relationship.json")
    public ResultEntity<String> saveRoleAuthRelationShip(@RequestBody Map<String, List<Integer>> map) {

        authService.saveRoleAuthRelationShip(map);

        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("assign/get/assigned/auth/id/by/role/id.json")
    public ResultEntity<List<Integer>> getAssignedAuthIdByRoleId(@RequestParam("roleId") Integer roleId) {

        List<Integer> authIdList = authService.getAssignedAuthIdByRoleId(roleId);

        return ResultEntity.successWithData(authIdList);
    }

    @ResponseBody
    @RequestMapping("assign/get/all/auth.json")
    public ResultEntity<List<Auth>> getAllAuth() {

        List<Auth> authList = authService.getAll();

        return ResultEntity.successWithData(authList);
    }


    @RequestMapping("assign/to/page.html")
    public String toAssignRolePage(@RequestParam("adminId") Integer adminId, Model model) {

        // 查询已分配的角色
        List<Role> assignedRole = roleService.getAssignedRole(adminId);
        // 查询未分配的角色
        List<Role> unAssignedRole = roleService.getUnAssignedRole(adminId);
        // 存入request域
        model.addAttribute("assignedRole", assignedRole);
        model.addAttribute("unAssignedRole", unAssignedRole);

        return "assign-role";
    }

    @RequestMapping("assign/do/assign.html")
    public String saveRelationShip(@RequestParam("adminId") Integer adminId,
                                   @RequestParam("pageNum") Integer pageNum,
                                   @RequestParam("keyword") String keyword,
                                   @RequestParam(value = "roleList", required = false) List<Integer> roleList) {
        adminService.saveRelationShip(adminId, roleList);

        return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
    }

}
